<?php namespace App\Admin\Base;

trait IndexService {
    
    public function index(){
        if(env('APP_DEV')){
            $this->createApp();
        }
        return view('admin.index');
    }
    
    private function createFramwork(){
        $target = base_path('public/admin/js/framework.js');
        $frameworkPath = base_path('resources/views/core');
        $files = [];
        $this->getFiles($frameworkPath, $files);
        $fp = fopen($target, 'w+');
        foreach($files as $file){
            fwrite($fp, file_get_contents($file)."\r\n");
        }
        fclose($fp);
    }
    
    private function createApp(){
        $target = base_path('public/admin/js/app.js');
        $adminPath = base_path('resources/views/admin');       
        $clientPath = base_path('resources/views/client');       
        $files = [];
        $this->getFiles($adminPath, $files);
        $this->getFiles($clientPath, $files);
        $fp = fopen($target, 'w+');
        foreach($files as $key => $file){
            if(strpos($file, '/models/') !== false){
                unset($files[$key]);
                fwrite($fp, file_get_contents($file)."\r\n");
            }
        }
        foreach($files as $file){

            fwrite($fp, file_get_contents($file)."\r\n");
        }
        fclose($fp);
    }
    
    private function getFiles($path, &$files){
        if(is_dir($path)){
            $dp = dir($path);
            while($file = $dp->read()){
                if($file!='.'&& $file!='..'){
                    $this->getFiles($path.'/'.$file, $files);
                }
            }
            $dp->close();
        }
        if(is_file($path) && basename($path) === 'include.json'){
            $filesMap = json_decode(file_get_contents($path));
            $basePath = dirname($path);
            foreach($filesMap as $val){
                if(!is_array($val)){
                    $files[] = $basePath.'/'.$val;
                    continue;
                }
                foreach($val as $val1){
                    $files[] = $basePath.'/'.$val1;
                }
            }
        }
    }
}